//并发
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <chrono>
#include <iomanip>

std::mutex mtx;  // 用于保护共享资源

void partialSquareSum(int index,long long result) {
    long long partialSum = 0;
    for (size_t i = 0; i < 100000000; ++i) {
        partialSum += 2 * 2;
    }

    {
        std::lock_guard<std::mutex> lock(mtx);
        result += partialSum;
    }
   // 获取当前时间并格式化
    auto now = std::chrono::system_clock::now();
    auto now_ms = std::chrono::time_point_cast<std::chrono::microseconds>(now);  // 获取微秒级时间戳
    auto epoch = now_ms.time_since_epoch();
    auto seconds = std::chrono::duration_cast<std::chrono::seconds>(epoch);
    auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(epoch) - std::chrono::duration_cast<std::chrono::microseconds>(seconds);

    std::time_t now_c = std::chrono::system_clock::to_time_t(now);
    std::tm tm;
    localtime_s(&tm, &now_c);

    // 打印线程的结果和时间戳（精确到微秒）
    std::cout << "thread" << index << ": time: " << partialSum 
               << " time: " << std::put_time(&tm, "%Y-%m-%d %H:%M:%S") 
               << "." << std::setw(6) << std::setfill('0') << microseconds.count() << std::endl;
}

int main() {
    long long result = 0;

    // 定义线程数量
    const int threadCount = 3;
    std::vector<std::thread> threads;

    for (int i = 0; i < threadCount; ++i) {
        // 创建线程并传入参数，注意 partialSquareSum 的参数顺序
        threads.emplace_back(partialSquareSum, i + 1,result);
    }

    for (auto& t : threads) {
        t.join();  // 等待所有线程完成
    }

    std::cout << "concurrency: " << result << std::endl;

    return 0;
}
